// pages/index/index.js
const app = getApp()

Page({
  data: {
    products: [
      {
        id: 4,
        name: "🍯烧仙草🍯",
        price: 15,
        image: "/pages/diancan/image/shaoxian.jpg"
      },

      // 你可以继续添加其他商品
    ],
    cart: [],
    totalPrice: 0
  },

  onLoad() {
    this.setData({
      cart: app.globalData.cart || []
    })
    this.updateTotalPrice()
  },

  // 添加商品到购物车
  addToCart(event) {
    const productId = event.currentTarget.dataset.id
    const product = this.data.products.find(item => item.id === productId)
    
    let cart = this.data.cart
    const existingProduct = cart.find(item => item.id === product.id)

    if (existingProduct) {
      existingProduct.quantity++
      existingProduct.totalPrice = existingProduct.quantity * existingProduct.price
    } else {
      cart.push({
        id: product.id,
        name: product.name,
        price: product.price,
        quantity: 1,
        totalPrice: product.price
      })
    }

    this.setData({ cart })
    app.globalData.cart = cart
    this.updateTotalPrice()
  },

  // 从购物车中移除商品
  removeFromCart(event) {
    const productId = event.currentTarget.dataset.id
    let cart = this.data.cart

    cart = cart.filter(item => item.id !== productId)

    this.setData({ cart })
    app.globalData.cart = cart
    this.updateTotalPrice()
  },

  // 清空购物车
  clearCart() {
    this.setData({
      cart: []
    })
    app.globalData.cart = []
    this.updateTotalPrice()
  },

  // 更新购物车总价
  updateTotalPrice() {
    const totalPrice = this.data.cart.reduce((total, item) => total + item.totalPrice, 0)
    this.setData({ totalPrice })
  }
})
